﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace AdminCreatFile
{
    class AdminCreatFile
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("hello world");
            try
            {
                FileStream fileStream = new FileStream(args[0], FileMode.Create);
                fileStream.Close();
                SetFilePermission(args[0], "Users");
            }
            catch
            {
                //Console.WriteLine("creat file error");
                return;
            }
            try
            {
                using (StreamWriter sr = new StreamWriter(args[0]))
                {
                    sr.WriteLine(args[1].Replace("'", @""""));
                    sr.Close();
                }
            }
            catch
            {
                //Console.WriteLine("write file error");
                return;
            }
            //Console.ReadKey();
        }

        /// <summary>
        /// 将账户对文件的访问权限设置为完全访问
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="userName">账户名</param>
        private static void SetFilePermission(string filePath, string userName)
        {
            FileInfo fi = new FileInfo(filePath);
            FileSecurity fileSecurity = fi.GetAccessControl();
            fileSecurity.AddAccessRule
                (new FileSystemAccessRule
                    (userName, FileSystemRights.FullControl,
                    AccessControlType.Allow));
            fi.SetAccessControl(fileSecurity);
        }
    }
}
